﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;
using MotionControl.Modules.LightSource.LightControl;
using Newtonsoft.Json;

namespace MotionControl.Modules.LightSource.Models
{
    public enum LightType
    {
        KW  = 0,
        OPT = 1
    }

    [JsonObject(MemberSerialization.OptIn)]
    public class Light
    {
        public Light(string comName, LightType type, int channelNum)
        {
            ComName = comName;
            Type = type;
            switch (type)
            {
                case LightType.KW:
                    lightObj = new JCKwLight(comName, channelNum);
                    break;
                case LightType.OPT:
                    lightObj = new JCOptLight(comName, channelNum);
                    break;
            }
            //Channels = new ChannelList();
            //Channels.CollectionChanged += OnItemAdded;
            lightObj.InitLight();
        }

        ~Light()
        {
            lightObj.DisConnect();
        }

        [JsonProperty]
        public string ComName { get; }

        [JsonProperty]
        public LightType Type { get; }

        [JsonProperty]
        public ChannelList Channels { get; set; }

        public void ConnectChannelToLight()
        {
            foreach (var channel in Channels) {
                channel.IntensityChanged += OnIntensityChanged;
                channel.SwitchingChanged += OnSwitchingChanged;
            }
        }
        public void AddChannel(Channel ch) {
            Channels.Add(ch);
            ch.IntensityChanged += OnIntensityChanged;
            ch.SwitchingChanged += OnSwitchingChanged;
        }
        private void OnItemAdded(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                foreach (var item in e.NewItems)
                {
                    ((Channel)item).IntensityChanged += OnIntensityChanged;
                    ((Channel)item).SwitchingChanged += OnSwitchingChanged;
                }
            }
        }
        void OnIntensityChanged(int num, int val)
        {
            lightObj.SetIntensity(num, val);
            //var ret = 0;
            //lightObj.GetIntensity(num, out ret);
        }
        void OnSwitchingChanged(int num, bool isOpen)
        {
            if (isOpen)
            {
                lightObj.TurnOnChannel(num);
                Debug.WriteLine("Turn On Channel:{0}", num);
            }

            else
            {
                lightObj.TurnOffChannel(num);
                Debug.WriteLine("Turn Off Channel:{0}", num);
            }
                
        }
        private readonly IJFLight lightObj;

        public override string ToString() => ComName;
    }
}
